<template>
	<div class="need-edit-container">
		<el-card class="box-card">
			<div slot="header" class="card-header">
				<span>埋点需求信息（ID：{{this.id}}）<span class="link" @click="handleOpenDialog">公共属性</span></span>
				<div class="card-header-btn">
					<el-button size="mini" type="primary" @click="handleSubmit">提交</el-button>
					<el-button size="mini" type="primary" @click="handleSaveRequirement">保存</el-button>
				</div>
			</div>
			<el-form ref="form" :model="form" :rules="formRules" label-width="110px" size="mini" class="requirement-form">
				<el-row>
					<el-col :span="8">
						<el-form-item label="需求名称:" prop="requirementName">
							<el-input v-model="form.requirementName"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="系统版本" prop="versionId">
							<el-select v-model="form.versionId" placeholder="请选择版本">
								<el-option v-for="item in versionList"
													 :label="item.version"
													 :key="item.id"
													 :value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="埋点SDK类型:" prop="sdkType">
							<el-select v-model="form.sdkType" disabled>
								<el-option v-for="item in $sdkTypeList"
													 :key="item.value"
													 :value="item.value"
													 :label="item.label">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="应用:" prop="appId">
							<el-select v-model="form.appId" disabled>
								<el-option v-for="item in appSelectList"
													 :key="item.appId"
													 :value="item.appId"
													 :label="item.appName">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="栏目:" prop="bizId">
							<el-select v-model="form.bizId" disabled>
								<el-option v-for="item in bizSelectList"
													 :key="item.bizId"
													 :value="item.bizId"
													 :label="item.bizName">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="产品编码:" prop="productCode">
							<el-select v-model="form.productCode" disabled>
								<el-option v-for="item in $productCodeList"
													 :key="item.value"
													 :value="item.value"
													 :label="item.label">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="需求描述:" prop="desc">
							<el-input type="textarea" v-model="form.desc"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<el-card class="box-card tab-card">
			<el-button type="text" size="small" class="sync-need-btn" @click="handleSyncNeed">同步需求</el-button>
			<el-tabs v-model="tabActive">
				<el-tab-pane label="位置列表" name="first" class="page-content">
					<div class="msg">
						<div>有明确位置的埋点请先
							<span class="link" @click="handlePageLink">添加位置</span>
							，无明确位置的埋点请添加
							<span class="link" @click="handleOpenDrawer">全局埋点</span></div>
					</div>
					<div class="msg">
						<div class="search">
							<el-input placeholder="位置名称" size="mini" v-model="searchPage.pageName"></el-input>
							<el-input placeholder="位置标识" size="mini" v-model="searchPage.pageId"></el-input>
							<el-select size="mini" clearable multiple placeholder="位置类型" v-model="searchPage.pageType">
								<el-option
									v-for="item in $pageTypeList"
									:key="item.value"
									:label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
							<el-select size="mini" clearable multiple placeholder="需求类型" v-model="searchPage.requirementType">
								<el-option
									v-for="(val, key) in $requirementTypeObj"
									:key="key"
									:label="val"
									:value="key">
								</el-option>
							</el-select>
							<el-button size="mini" type="primary" @click="handleSearchPage">查询</el-button>
						</div>
						<div>
							<el-button size="mini" type="primary" class="edit-btn" @click="handlePageLink">编辑位置埋点</el-button>
						</div>
					</div>

					<el-table
						size="mini"
						border
						:data="pageTableData"
						style="width: 100%"
						v-loading="pageTableLoading"
						row-key="id"
						lazy
						:load="handleLoadPage"
						:tree-props="{children: 'children', hasChildren: 'hasChildren'}">
						<el-table-column
							v-for="item in pageColumns"
							:show-overflow-tooltip="true"
							:sortable="item.sortable"
							:key="item.prop"
							:prop="item.prop"
							:label="item.label"
							:min-width="item.width">
							<template slot-scope="scope">
								<span v-if="item.prop === 'pageType'">
									{{$pageTypeObj[scope.row[item.prop]] || "--"}}
								</span>
								<span
									v-else-if="item.prop === 'requirementType'"
									:class="'requirement-type-' + scope.row[item.prop]">
									{{$handleRequirementType(scope.row[item.prop]) || "--"}}
								</span>
								<span v-else>{{scope.row[item.prop] || "--"}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="action" label="操作" width="100">
							<template slot-scope="scope">
								<el-button
									size="mini"
									type="text"
									v-if="handleShowAction(scope, 'edit')"
									@click="handleEditPage(scope)">编辑
								</el-button>
								<el-button
									size="mini"
									type="text"
									v-if="handleShowAction(scope, 'delete')"
									@click="handlePageStatus(scope, '删除', 0)">删除
								</el-button>
								<el-button
									size="mini"
									type="text"
									v-if="handleShowAction(scope, 'offline')"
									@click="handlePageStatus(scope, '下线', 1)">下线
								</el-button>
								<el-button
									size="mini"
									type="text"
									v-if="handleShowAction(scope, 'online')"
									@click="handlePageStatus(scope, '取消下线', 2)">取消下线
								</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination
						@size-change="handleSizeChangePage"
						@current-change="handleCurrentChangePage"
						:current-page="searchPage.currentPage"
						:page-sizes="[10, 20, 30, 40]"
						:page-size="searchPage.pageSize"
						background
						layout="total, prev, pager, next, sizes, jumper"
						:total="pageTableTotal">
					</el-pagination>
				</el-tab-pane>
				<el-tab-pane label="埋点列表" name="second" class="un-page-content">
					<div class="msg">
						<div class="search">
							<el-input v-model="searchEvent.trackName" size="mini" placeholder="埋点名称"></el-input>
							<el-input v-model="searchEvent.trackId" size="mini" placeholder="埋点标识"></el-input>
							<el-input v-model="searchEvent.eventId" size="mini" placeholder="事件名称"></el-input>
							<el-select size="mini" clearable placeholder="有无位置" v-model="searchEvent.hasPosition">
								<el-option
									v-for="(item, index) in hasPositionList"
									:key="index"
									:label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
							<el-select size="mini" clearable multiple placeholder="需求类型" v-model="searchEvent.requirementType">
								<el-option
									v-for="(val, key) in $requirementTypeObj"
									:key="key"
									:label="val"
									:value="key">
								</el-option>
							</el-select>
							<el-button size="mini" type="primary" @click="handleSearchEvent">查询</el-button>
						</div>
						<div>
							<el-button size="mini" type="primary" class="edit-btn" @click="handleOpenDrawer">添加无位置埋点</el-button>
						</div>
					</div>
					<el-table size="mini" border :data="eventTableData" style="width: 100%" v-loading="eventTableLoading">
						<el-table-column
							v-for="item in eventColumns"
							:show-overflow-tooltip="true"
							:sortable="item.sortable"
							:key="item.prop"
							:min-width="item.width"
							:prop="item.prop"
							:label="item.label">
							<template slot-scope="scope">
								<span v-if="item.prop === 'requirementType'" :class="'requirement-type-' + scope.row[item.prop]">{{$handleRequirementType(scope.row[item.prop]) || "--"}}</span>
								<span v-else>{{scope.row[item.prop] || "--"}}</span>
							</template>
						</el-table-column>
						<el-table-column prop="action" label="操作" width="100">
							<template slot-scope="scope">
								<el-button
									size="mini"
									type="text"
									v-if="handleShowAction(scope, 'edit', 'track')"
									@click="handleEditDrawer(scope)">编辑
								</el-button>
								<el-button
									size="mini"
									type="text"
									v-if="handleShowAction(scope, 'delete')"
									@click="handleEventStatus(scope, '删除', 0)">删除
								</el-button>
								<el-button
									size="mini"
									type="text"
									v-if="handleShowAction(scope, 'offline')"
									@click="handleEventStatus(scope, '下线', 1)">下线
								</el-button>
								<el-button
									size="mini"
									type="text"
									v-if="handleShowAction(scope, 'online')"
									@click="handleEventStatus(scope, '取消下线', 2)">取消下线
								</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination
						@size-change="handleSizeChangeEvent"
						@current-change="handleCurrentChangeEvent"
						:current-page="searchEvent.currentPage"
						:page-sizes="[10, 20, 30, 40]"
						:page-size="searchEvent.pageSize"
						background
						layout="total, prev, pager, next, sizes, jumper"
						:total="eventTableTotal">
					</el-pagination>
				</el-tab-pane>
			</el-tabs>
		</el-card>
		<el-dialog
			title="选择要同步的需求"
			:visible.sync="syncDialogVisible"
			width="40%">
			<p>将从下面选择的需求中同步位置和埋点到当前需求，当前需求下已有的位置和埋点将被删除！</p>
			<el-select style="width: 100%;" v-model="syncId">
				<el-option
					v-for="item in syncList"
					:label="item.requirementName"
					:value="item.id"
					:key="item.id">
				</el-option>
			</el-select>
			<span slot="footer" class="dialog-footer">
				<el-button size="mini" @click="syncDialogVisible = false">取 消</el-button>
				<el-button size="mini" type="primary" @click="handleSyncConfirm">确 定</el-button>
			</span>
		</el-dialog>
		<bury-form-module :info="buryDrawerInfo" @saveEvent="handleSaveEvent"></bury-form-module>
		<bury-form-module :info="dialogInfo" @saveProperties="handleSaveProperties"></bury-form-module>
	</div>
</template>

<script>
	export default {
		name: "needEdit",
		data() {
			return {
				id: null,
				requirementId: null,
				versionList: [],
				form: {},
				formRules: {
					requirementName: [
						{required: true, message: '请填写需求名称', trigger: 'blur'},
					],
					subType: [
						{required: true, message: '请选择类型', trigger: 'change'},
					],
					bizId: [
						{required: true, message: '请选择栏目', trigger: 'change'},
					],
					versionId: [
						{required: true, message: '请选择系统版本', trigger: 'change'},
					],
					productCode: [
						{required: true, message: '请选择产品编码', trigger: 'change'},
					],
				},
				tabActive: "first",
				trackName: "",
				level: 1,
				// 位置表格各项
				pageColumns: [
					{
						prop: "pageName",
						label: "位置名称",
						width: 100
					},
					{
						prop: "pageId",
						label: "位置标识",
						width: 100
					},
					{
						prop: "pageType",
						label: "位置类型",
						width: 80
					},
					{
						prop: "requirementType",
						label: "需求类型",
						width: 80
					},
					{
						prop: "subEventNum",
						label: "下级埋点(新增/修改/删除)",
						width: 100
					}
				],
				pageTableData: [],
				pageTableLoading: false,
				pageTableTotal: 0,
				childPageTableData: [],
				childPageTableLoading: false,
				// 埋点表格各项
				eventColumns: [
					{
						prop: "trackName",
						label: "埋点全称",
						width: 100
					},
					{
						prop: "trackId",
						label: "埋点标识",
						width: 100
					},
					{
						prop: "eventId",
						label: "事件名称",
						width: 100
					},
					{
						prop: "eventName",
						label: "事件显示名称",
						width: 100
					},
					{
						prop: "requirementType",
						label: "需求类型",
						width: 100
					},
				],
				eventTableData: [],
				eventTableLoading: false,
				eventTableTotal: 0,
				// 有无位置list
				hasPositionList: [
					{
						value: true,
						label: "有"
					},
					{
						value: null,
						label: "无"
					},
				],
				// 埋点查询
				searchEvent: {
					currentPage: 1,
					pageSize: 10,
					trackId: "",
					hasPosition: "",
					trackName: "",
					eventId: "",
					requirementType: []
				},
				// 位置查询
				searchPage: {
					// pageName: "",
					// pageId: "",
					// pageType: "",
					// requirementType: "",
					requirementType: [],
					pageType: [],
					currentPage: 1,
					pageSize: 10,
				},
				// 同步需求
				syncDialogVisible: false,
				syncId: null,
				syncList: [],
				//    无位置列表
				//    drawer: 埋点
				buryDrawerInfo: {
					requirementId: null,
					trackDbId: null,
					type: null
				},
				dialogInfo: {
					requirementId: null,
					type: null,
					isAction: true
				}
			}
		},
		components: {},
		computed: {
			appSelectList() {
				return this.$store.state.publicData.appSelectList;
			},
			bizSelectList() {
				return this.$store.state.publicData.bizSelectList;
			}
		},
		created() {
			this.$store.dispatch("getAppSelectList");
			this.$store.dispatch("getBizSelectList", {hasEventCollectData: false, needSimpleData: true});
			let {id} = this.$route.params;
			this.id = unescape(id);
			this.handleQueryRequirement();
		},
		mounted() {
		},
		methods: {
			// 查询需求详情
			async handleQueryRequirement() {
				let data = {
					id: this.id
				}
				let res = await this.$requirementApi.requirementQuery(data);
				if (res) {
					let {requirementId, publicProperties, sdkType, appId} = res.value;
					this.requirementId = requirementId;
					publicProperties = publicProperties ? JSON.parse(publicProperties) : [];
					this.form = {
						...res.value,
						publicProperties: publicProperties
					}
					if (sdkType === 3 || sdkType === 4) {
						this.formRules.version = [];
					} else {
						this.formRules.version = [
							{required: true, message: '请填写系统版本', trigger: 'blur'},
						];
					}
					this.handleQueryPageList();
					this.handleEventList();
					this.handleQueryVersionList(appId);
				}
			},
			// 版本列表
			async handleQueryVersionList(appId) {
				let data = {
					appId
				};
				let res = await this.$requirementApi.versionList(data);
				if (res) {
					let {list} = res.value;
					this.versionList = list;
				}
			},
			// 提交需求
			async handleSubmit() {
				this.$confirm(`提交后需求状态将变成实施中，您确定要提交该需求吗？`, "提交需求", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.handleRequirementStatus();
				}).catch(() => {
				})
			},
			async handleRequirementStatus() {
				let data = {
					requirementId: this.requirementId,
					nowStage: this.form.status,
					targetStage: 2,
					action: "提交",
				};
				let res = await this.$processApi.processAdd(data);
				if (res) {
					this.$message.success("提交成功");
					this.$router.push({
						path: "/buryNeed/list"
					});
				}
			},
			// 保存需求
			async handleSaveRequirement() {
				let res = await this.$requirementApi.requirementUpdate(this.form);
				if (res.success) {
					this.$message({
						type: "success",
						message: "保存成功",
						offset:60
					});
				}
			},
			// 位置展开，load数据
			async handleLoadPage(tree, treeNode, resolve) {
				let {id, level} = tree;
				level = level + 1;
				console.log(level);
				if (level <= 3) {
					let data = {
						parentId: id,
						currentPage: 1,
						pageSize: 10000,
						level: level,
						requirementId: this.requirementId,
					}
					let res = await this.$pageApi.pageList(data);
					if (res) {
						let {list} = res.value;
						if (level < 3) {
							list.forEach(item => {
								item.hasChildren = true;
							});
						}
						resolve(list);
					}
				} else {
					resolve([]);
				}

			},
			// 位置：点击查询
			handleSearchPage() {
				this.searchPage.currentPage = 1;
				this.handleQueryPageList();
			},
			// 位置列表
			async handleQueryPageList() {
				this.pageTableLoading = true;
				try {
					let {pageName, pageId, pageType} = this.searchPage;
					let data = {
						...this.searchPage,
						level: 1,
						requirementId: this.requirementId,
					};
					let res = await this.$pageApi.pageList(data);
					if (res) {
						let {list, total} = res.value;
						if (!pageName && !pageId && pageType.length === 0) {
							list.forEach(item => {
								item.hasChildren = true;
							});
						}
						this.pageTableData = list;
						this.pageTableTotal = total;
					}
					this.pageTableLoading = false;
				} catch (err) {
					this.pageTableLoading = false;
				}
			},
			handleCurrentChangePage(page) {
				this.searchPage.currentPage = page;
				this.handleQueryPageList();
			},
			handleSizeChangePage(size) {
				this.searchPage.currentPage = 1;
				this.searchPage.pageSize = size;
				this.handleQueryPageList();
			},
			// 搜索埋点
			handleSearchEvent() {
				this.searchEvent.currentPage = 1;
				this.handleEventList();
			},
			// 埋点列表
			async handleEventList() {
				this.eventTableLoading = true;
				let {eventId} = this.searchEvent;
				try {
					let data = {
						...this.searchEvent,
						eventId: eventId ? [eventId] : [],
						requirementId: this.requirementId
					}
					let res = await this.$eventApi.eventList(data);
					if (res) {
						let {list, total} = res.value;
						this.eventTableData = list;
						this.eventTableTotal = total;
					}
					this.eventTableLoading = false;
				} catch (e) {
					this.eventTableLoading = true;
				}
			},
			handleCurrentChangeEvent(page) {
				this.searchEvent.currentPage = page;
				this.handleEventList();
			},
			handleSizeChangeEvent(size) {
				this.searchEvent.currentPage = 1;
				this.searchEvent.pageSize = size;
				this.handleEventList();
			},
			// 埋点操作类型
			handleShowAction(scope, type, tabType) {
				let {requirementType, processStatus, status} = scope.row;
				requirementType = Number(requirementType);
				if (type === "edit") {
					if (tabType === "track") {
						return (requirementType === 0 || requirementType === 1 || requirementType === 2) && (processStatus == 0 || status == 1);
					} else {
						return (requirementType === 0 || requirementType === 1 || requirementType === 2);
					}
				} else if (type === "delete") {
					return (requirementType === 1);
				} else if (type === "offline") {
					return (requirementType === 0 || requirementType === 2)
				} else if (type === "online") {
					return (requirementType === 3 || requirementType === 4);
				}
			},
			// 编辑
			handleEditPage(scope) {
				let {id} = scope.row;
				sessionStorage.setItem("rq_record_id", this.id);
				this.$router.push({path: "/buryNeed/edit/" + escape(this.id) + "/item/" + escape(id)});
			},
			// 更新位置状态
			handlePageStatus(scope, type, operateType) {
				this.$confirm(`您确定要${type}该位置吗？`, type, {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.handlePageStatusOperate(scope, type, operateType);
				}).catch(() => {
				})
			},
			// 接口：位置状态变更
			async handlePageStatusOperate(scope, type, operateType) {
				let {id} = scope.row;
				let data = {
					id,
					operateType
				}
				let res = await this.$pageApi.pageStatusOperate(data);
				if (res) {
					this.$message({
						type: 'success',
						message: type + '成功!'
					});
					this.handleQueryPageList();
				}
			},
			// 更新埋点状态
			handleEventStatus(scope, type, operateType) {
				this.$confirm(`您确定要${type}该埋点吗？`, type, {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.handleEventStatusUpdate(scope, type, operateType);
				}).catch(() => {
				})
			},
			// 接口：埋点状态变更
			async handleEventStatusUpdate(scope, type, operateType) {
				let {id} = scope.row;
				let data = {
					id,
					operateType
				}
				let res = await this.$eventApi.eventStatusUpdate(data);
				if (res) {
					this.$message({
						type: 'success',
						message: type + '成功!'
					});
					this.handleEventList();
				}
			},
			// 同步需求列表
			async handleQuerySyncList() {
				let {bizId, sdkType, productCode} = this.form;
				let data = {
					bizId,
					sdkType,
					productCode
				};
				let res = await this.$requirementApi.requirementSyncList(data);
				if (res) {
					this.syncList = res.value.list;
				}
			},
			// 同步需求：打开
			handleSyncNeed() {
				this.handleQuerySyncList();
				this.syncDialogVisible = true;
			},
			// 同步需求：保存
			async handleSyncConfirm() {
				let data = {
					targetId: this.syncId,
					toBeSyncId: this.id
				}
				let res = await this.$requirementApi.requirementSync(data);
				if (res) {
					this.$message({
						type: 'success',
						message: '同步需求成功!'
					});
					this.syncDialogVisible = false;
				}
			},
			// 编辑位置埋点
			handlePageLink() {
				sessionStorage.setItem("rq_record_id", this.id);
				let id = escape(this.id);
				this.$router.push({
					path: `/buryNeed/edit/${id}/item`
				})
			},
			// 无位置埋点
			// 打开埋点drawer：添加
			handleOpenDrawer() {
				this.buryDrawerInfo = {
					requirementId: this.requirementId,
					trackDbId: null,
					type: "drawer",
				};
			},
			// 打开埋点drawer：修改
			handleEditDrawer(scope) {
				let {id, pageDO} = scope.row;
				this.buryDrawerInfo = {
					requirementId: this.requirementId,
					trackDbId: id,
					type: "drawer",
					imageUrl: pageDO ? pageDO.imageUrl : ""
				};
			},
			handleSaveEvent(status) {
				if (status) {
					this.handleEventList();
				}
			},
			// 公共属性：打开dialog
			handleOpenDialog() {
				this.dialogInfo = {
					requirementId: this.requirementId,
					type: "dialog",
					publicProperties: this.form.publicProperties || [],
					isAction: true
				}
			},
			// 前端：保存公共属性
			handleSaveProperties(val) {
				this.form.publicProperties = val;
			}
		},
		watch: {}
	}
</script>

<style lang="scss">
	.need-edit-container {
		.el-card__body {
			padding: 0;
		}

		.el-form.requirement-form {
			padding: 20px 20px 0 20px;
		}

		.tab-card {
			margin-top: 15px;
			position: relative;

			.sync-need-btn {
				position: absolute;
				right: 20px;
				height: 40px;
				cursor: pointer;
				z-index: 10;
			}

			.el-tabs {
				padding: 0 20px;

				.msg {
					font-size: 12px;
					display: -webkit-box;
					display: -moz-box;
					display: -ms-flexbox;
					display: -webkit-flex;
					display: flex;
					-webkit-box-pack: justify;
					-moz-justify-content: space-between;
					-webkit-justify-content: space-between;
					justify-content: space-between;
					-webkit-box-align: center;
					-moz-align-items: center;
					-webkit-align-items: center;
					align-items: center;

					.el-input {
						width: 350px;
					}
				}

				.search {
					.el-input {
						width: 170px;
						margin: 5px 8px 5px 0;
					}
				}
			}
		}
	}
</style>
